package com.sayi.dzapi.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

import com.sayi.dzapi.annotation.CheckBrowser;

@Component
public class CheckBrowserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();

            // 检查方法上是否有@CheckBrowser注解
            if (method.isAnnotationPresent(CheckBrowser.class)) {
                CheckBrowser annotation = method.getAnnotation(CheckBrowser.class);

                // 检查请求是否来自浏览器
                String userAgent = request.getHeader("User-Agent");
                if (userAgent != null && userAgent.contains("Mozilla")) {
                    response.setStatus(annotation.browserCheckFailedStatus());
                    response.getWriter().write(annotation.browserCheckFailedMessage());
                    return false;
                }
            }
        }
        return true;
    }
}
